package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.advanced;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.http.client.AbstractHandleHttpDistributeClientProxyServerTransferTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;

/**
 * http 远程代理
 * 客户端：客户端远程到服务端、客户端远程到客户端
 */
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
public class ClientHandleDistributeHttpClientProxyServerTransferTypeAdvanced extends
        AbstractHandleHttpDistributeClientProxyServerTransferTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param nettyChannelContext       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {

        Channel channel = nettyChannelContext.channel();

        String visitorId = ChannelAttributeKeyUtils.getVisitorId(channel);
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
        if (nextChannel == null) {
            log.error("无法获取访客:{} 真实服务", visitorId);
            return;
        }

        // 把数据转到真实服务
        ByteBuf buf = channel.config().getAllocator().buffer(nettyProxyMsg.getData().length);
        buf.writeBytes(nettyProxyMsg.getData());

        nextChannel.writeAndFlush(buf);

    }
}
